'use strict';

/**
 * @ngdoc function
 * @name magisterkaGuiApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the magisterkaGuiApp
 */
angular.module('magisterkaGuiApp')
    .controller('MainCtrl', function ($scope, $log, Facebook,$http) {
        $scope.getLikes = getLikes;
        $scope.likes = {};
        $scope.event = {objectId: '870026676390291'};

        function fetchLikes(url) {
            $scope.finishedLoadingLikes=false;
            Facebook.api(url, {limit: 1000, summary: true}, likesHandler);
        }

        function likesHandler(response) {
            $log.info('Likes handler response:',response);
            $scope.likes.results = $scope.likes.results.concat(response.data);
            $scope.$apply();
            var nextUrl = response.paging.next;
            if (nextUrl) {
                fetchLikes(nextUrl);
            }else{
                $scope.finishedLoadingLikes=true;
            }
        }

        //should abort previous calls
        function getLikes() {
            $scope.likes.results = [];

            var url = '/v2.3/' + $scope.event.objectId + '/likes?access_token=902389696451149|02a243421d395178549bc83445000627&fields=id,name,picture';
            fetchLikes(url);
        }

        $scope.startContest = function(){
            $http.get('resources/cars_contest_first_response.json').then(function(response){
                var peopleProgress=response.data.data;
                $log.info('People progress: ',peopleProgress);
                angular.forEach(peopleProgress,function(progressData){
                    angular.forEach($scope.likes.results,function(personData){
                       if(progressData.id==personData.id){
                           personData.percentFinished=progressData.percentFinished?progressData.percentFinished:0;
                       }
                    });
                });
                $log.info('Results after matching percent finished',$scope.likes.results);
            });
        }

        getLikes(); //for debugging purposes
    });
